package coin

import (
	"global/core"
	"fmt"
	"github.com/parnurzeal/gorequest"
	"global/constants"
	"strings"
	"github.com/ngaut/log"
	"srv/cmc/cap"
)

// 从 CoinMarketCap 获取所有币种数据

type CoinAction struct {
	Ctx 			*core.Context
	BaseUrl 		string
	Key 			string
}

func NewCmcCoin() cap.InterfaceCmc {
	return &CoinAction{}
}

func (a *CoinAction) Run() error {
	a.get()
	return nil
}

func (a *CoinAction) Init(ctx *core.Context) cap.InterfaceCmc {
	a.Ctx = ctx
	debug := a.Ctx.IsDebug()
	if debug {
		a.BaseUrl = constants.CmcSandboxBaseUrl
	} else {
		a.BaseUrl = constants.CmcProductionBaseUrl
	}
	log.Infof("Debug: %v", debug)

	key := a.Ctx.AccountConfig()
	a.Key = key
	return a
}

// 获取URL
func (a *CoinAction) url(uri string) string {
	baseUrl := strings.TrimRight(a.BaseUrl, "/") + "/"
	uri = strings.TrimLeft(uri, "/")
	return fmt.Sprintf("%s%s", baseUrl, uri)
}

func (a *CoinAction) get() {
	log.Infof("Key: %s", a.Key)
	r := gorequest.New()
	_, body, errs := r.Get(a.url(constants.CmcGetMarketQuotesUrl)).
		Set("X-CMC_PRO_API_KEY", a.Key).
		Query(map[string]interface{}{
			"id": "1",
			"convert": "BTC,USD,CNY",
		}).
		End()
	if len(errs) != 0 {
		log.Errorf("Error: request market quote failed, msg: %s", errs[0])
	}
	log.Infof("Body: %s", string(body))
}